package cn.turboinfo.fuyang.api.gateway.admin.controller.company;


import cn.turboinfo.fuyang.api.domain.admin.usecase.company.HousekeepingCompanySearchUseCase;
import cn.turboinfo.fuyang.api.domain.common.service.file.FileAttachmentService;
import cn.turboinfo.fuyang.api.domain.web.component.file.FileAttachmentHelper;
import cn.turboinfo.fuyang.api.entity.common.pojo.company.HousekeepingCompany;
import cn.turboinfo.fuyang.api.entity.common.pojo.company.QHousekeepingCompany;
import cn.turboinfo.fuyang.api.entity.common.pojo.file.FileAttachment;
import cn.turboinfo.fuyang.api.gateway.admin.fo.company.HousekeepingCompanySearchFO;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.ResponseBodyWrapper;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.context.AdminRequestContext;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.fo.LimitDataFO;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.fo.LimitFO;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.fo.SortFO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.qbean.api.request.QRequest;
import net.sunshow.toolkit.core.qbean.api.request.QSort;
import net.sunshow.toolkit.core.qbean.helper.component.request.QBeanSearchHelper;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 家政公司管理
 */
@Slf4j
@RequiredArgsConstructor
@Controller
@ResponseBodyWrapper
@RequestMapping("/admin/company")
public class HousekeepingCompanyController {

    private final HousekeepingCompanySearchUseCase housekeepingCompanySearchUseCase;
    private final FileAttachmentHelper fileAttachmentHelper;
    private final FileAttachmentService fileAttachmentService;

    @RequiresPermissions("company:list")
    @RequestMapping("/list")
    public LimitDataFO<HousekeepingCompany> list(@Valid HousekeepingCompanySearchFO search, LimitFO page, SortFO sort, AdminRequestContext context) {

        QRequest request = QBeanSearchHelper.convertQRequest(search);

        if (sort.getSortFields() == null) {
            sort.setSortFields(new String[]{QHousekeepingCompany.id + "|" + QSort.Order.DESC.name()});
        }
        HousekeepingCompanySearchUseCase.OutputData outputData = housekeepingCompanySearchUseCase.execute(HousekeepingCompanySearchUseCase.InputData
                .builder()
                .userId(context.getUserId())
                .request(request)
                .requestPage(page.toQPage(sort.toQSortList()))
                .build());
        return LimitDataFO.fromQResponse(outputData.getQResponse());
    }

    /**
     * 下载文件
     *
     * @param fileAttachmentId
     * @param response
     * @throws IOException
     */
    @RequiresPermissions(value = {"company:list", "company:update", "company:view"}, logical = Logical.OR)
    @GetMapping("/downloadFile/{fileAttachmentId}")
    public void downloadAttachment(@PathVariable Long fileAttachmentId, HttpServletResponse response) throws IOException {
        FileAttachment fileAttachment = fileAttachmentService.getByIdEnsure(fileAttachmentId);

        File file = fileAttachmentHelper.readFileAttachment(fileAttachmentId);
        // 如果文件名存在，则进行下载
        if (file.exists()) {
            // 实现文件下载
            try (InputStream is = new FileInputStream(file);
                 OutputStream os = response.getOutputStream()) {
                // 配置文件下载
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(fileAttachment.getDisplayName(), StandardCharsets.UTF_8));
                IOUtils.copy(is, os);
                os.flush();
            }
        }
    }
}
